package com.work.chat.common.aspect;

import com.work.chat.common.annotataion.SystemLog;
import com.work.chat.common.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@Component
@Aspect
public class SystemLogAspect {

    @Autowired
    private HttpServletRequest request;

    //寻找切点：这里需要注意了，这个是将自己自定义注解作为切点的根据，路径一定要写正确了
    @Pointcut(value = "@annotation(com.work.chat.common.annotataion.SystemLog)")
    public void systemLog() {
    }

    //环绕通知
    @Around(value = "systemLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
        Long start = System.currentTimeMillis();
        Object proceed = null;
        //拿到方法
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        SystemLog annotation = methodSignature.getMethod().getAnnotation(SystemLog.class);
        try {
            proceed = proceedingJoinPoint.proceed();
            Long end = System.currentTimeMillis();
            log.info(">>>>>>>>>>>>开始{}执行成功：执行内容：{},执行时间：{}ms>>>>>>>>>>>>>>", annotation.title(), IpUtil.getIpAddress(request), end - start);
            return proceed;
        } catch (Throwable throwable) {
            Long end = System.currentTimeMillis();
            log.info(">>>>>>>>>>>>>>>>>>>开始{}执行失败：执行内容：{},执行时间：{}ms>>>>>>>>>>>>>>>>", annotation.title(), IpUtil.getIpAddress(request), end - start);
            throwable.printStackTrace();
            return null;
        }
    }
}
